<?php

namespace app\common\service\finance\FinanceScene;


use app\common\service\finance\FinanceManager;
use app\model\AgentBalanceLog;
use app\model\CouponOrder;
use think\Exception;

/**
 *
 */
class SupplierFailGoBack extends FinanceSceneBase  //说明文档：docs/已结算订单供应商失效处理方案.md
{
    protected $couponOrder;

    /**
     * @var AgentBalanceLog
     */
    protected $oldAgentBalanceLog;

    public function __construct(CouponOrder $couponOrder)
    {
        $this->couponOrder = $couponOrder;
    }


    public function handle():bool
    {
        try {

            $this->init();
            return true;

        }catch (Exception $exception){
            return  false;
        }

    }

    public function init(){

        $agentBalanceLog = AgentBalanceLog::query()
            ->where('agent_id', $this->agentId())
            ->whereIn('type', AgentBalanceLog::commission())
            ->where('quote_id', $this->quoteId())
            ->find();
        if (!$agentBalanceLog) {
            throw new Exception('没找到历史数据');
        }

        $this->oldAgentBalanceLog = $agentBalanceLog;

        //判断是否已经倒扣了记录了，如果已经扣除了，也报错

        $newAgentBalanceLog = AgentBalanceLog::query()
            ->where('agent_id', $this->agentId())
            ->whereIn('type', $this->type())
            ->where('quote_id', $this->quoteId())
            ->find();

        if ($newAgentBalanceLog){
            throw new Exception('已发生倒扣');
        }

    }



    public function moneyChange(): string
    {
        return FinanceManager::TYPE_DEC;
    }


    public function quoteId()
    {
        return $this->couponOrder->id;
    }


    public function agentId(): int
    {
        return $this->couponOrder->agent_id;
    }

    public function amount(): int
    {
        //找到当前订单，以前加过的钱是多少
        return $this->oldAgentBalanceLog->amount;

    }

    public function type(): int
    {
        return BALANCE_SUPPLIER_FIAL_GOBACK;
    }

    public function balanceType(): int
    {
        return FinanceManager::BALANCE_PROFIT;
    }

    public function remark()
    {
       return '订单倒扣扣款，订单id：'.$this->couponOrder->order_id;
    }
}